﻿/// <reference path="../Script (JScript)/SDK.REST.js"
/// <reference path="../Script (JScript)/SDK.Metadata.Query.vsdoc.js"
/// <reference path="../Script (JScript)/json2.js"


//
// page onload event
//
document.onreadystatechange = function () {
    if (document.readyState == "complete") {

        DXTools.QuickView.Config.Initialise();
    }
}


if (typeof (DXTools) == "undefined")
{ DXTools = { __namespace: true }; }
if (typeof (DXTools.QuickView) == "undefined")
{ DXTools.QuickView = { __namespace: true }; }
DXTools.QuickView.Config = {

    context : null,
    configXmlDoc: null,
    resourceXmlDoc: null,
    siteMapId : null,
    siteMapXml : null,
    quickViewMenuInSiteMap : false,

    loadCallStackCount: 0,

    //       
    // Initialises menu by loading config, resources and sitemap xml
    //
    Initialise: function () {

        this.ShowOverlay(true);

        // Grab global context
        this.context = GetGlobalContext();
        

        this.loadCallStackCount = 2;
        this.RetrieveSiteMap();
        this.RetrieveConfigAndResourceXML();

       
    },
    LoadActionComplete: function () {
        this.loadCallStackCount = this.loadCallStackCount - 1;
        if (this.loadCallStackCount <= 0) {

            this.InitialiseSecurityArea();

            this.ShowOverlay(false);
        }

    },

    RetrieveSiteMap: function () {
        // Retrieve sitemap xml
        //
        SDK.REST.retrieveMultipleRecords("SiteMap", "$select=SiteMapId,SiteMapXml",
                function (data) {

                    if (data[0] != null) {
                        this.DXTools.QuickView.Config.siteMapId = data[0].SiteMapId;
                        this.DXTools.QuickView.Config.siteMapXml = data[0].SiteMapXml;

                        if (this.DXTools.QuickView.Config.siteMapXml != null && this.DXTools.QuickView.Config.siteMapXml != "") {

                            this.DXTools.QuickView.Config.quickViewMenuInSiteMap = this.DXTools.QuickView.Config.IsQuickViewMenuInSiteMapXML(this.DXTools.QuickView.Config.siteMapXml);

                            if (this.DXTools.QuickView.Config.quickViewMenuInSiteMap) {
                                document.getElementById("uxSiteMapStatus").innerHTML = "Quick View Menu already added to SiteMap.";
                                document.getElementById("uxSiteMapUpdateButton").innerHTML = "Remove from SiteMap";
                            }
                            else {
                                document.getElementById("uxSiteMapStatus").innerHTML = "Quick View Menu not currently in SiteMap.";
                                document.getElementById("uxSiteMapUpdateButton").innerHTML = "Add to SiteMap";
                            }

                        }

                    }

                },
                function (error) {

                    alert(error);

                },
                function () {
                    this.DXTools.QuickView.Config.LoadActionComplete();
                });
    },

    RetrieveConfigAndResourceXML : function () {
        var config = this.LoadXMLDoc("QuickViewMenuConfig.xml");
        if (window.ActiveXObject) {
            if (config != null && config.xml != null) {
                this.configXmlDoc = this.ConvertXmlStringToDocument(config.xml);
            }
        }
        else {
            if (config != null ) {
                this.configXmlDoc = config.documentElement;
            }
        }
    
        //var resource = this.LoadXMLDoc("QuickViewMenuResources.xml");
        //if (window.ActiveXObject) {
        //    if (resource != null && resource.xml != null) {
        //        this.resourceXmlDoc = this.ConvertXmlStringToDocument(resource.xml);
        //    }
        //}
        //else {
        //    if (resource != null) {
        //        this.resourceXmlDoc = resource.documentElement;
        //    }
        //}

        this.LoadActionComplete();

    },

    InitialiseSecurityArea: function () {
        if (this.configXmlDoc != null) {
            if (this.configXmlDoc.selectSingleNode("//Config/Security[@Enabled='true']") != null) {
                // Security enabled
                document.getElementById("uxSecurityStatus").innerHTML = "Security enabled, menu buttons will show based on the user security privileges.";
                document.getElementById("uxSecurityUpdateButton").innerHTML = "Turn Off";
            }
            else {
                // Security disabled
                document.getElementById("uxSecurityStatus").innerHTML = "Security disabled, all menu buttons will show regardless of the user security privileges.";
                document.getElementById("uxSecurityUpdateButton").innerHTML = "Turn On";
            }
        }
    }
    ,
    IsQuickViewMenuInSiteMapXML : function (siteMapXml){

        var exists = false;

        var xmlDoc = this.ConvertXmlStringToDocument(siteMapXml);

        //var xmlDoc = new ActiveXObject('Msxml2.DOMDocument.6.0');
        //xmlDoc.loadXML(siteMapXml);

        if (xmlDoc != null) {
            if (xmlDoc.selectSingleNode("//SiteMap/Area[@Id='dxtools_QuickView_Area']") != null)
                exists = true;
        }

        return exists;

    },


    UpdateSiteMap : function(){

        this.ShowOverlay(true);


        var xmlDoc = this.ConvertXmlStringToDocument(this.siteMapXml);

        //var xmlDoc = new ActiveXObject('Msxml2.DOMDocument.6.0');
        //xmlDoc.loadXML(this.siteMapXml);

        if (xmlDoc != null) {
            if(this.quickViewMenuInSiteMap == true)
            {
                // remove it
                var node = xmlDoc.selectSingleNode("//SiteMap/Area[@Id='dxtools_QuickView_Area']");
                if (node != null) {
                   
                    xmlDoc.selectSingleNode("//SiteMap").removeChild(node);
                                       
                    var sXml  = this.GetXMLStringFromDocument(xmlDoc.selectSingleNode("//SiteMap"));
                    this.UploadSiteMap(sXml);

                    this.siteMapXml = sXml;
                    this.quickViewMenuInSiteMap = !this.quickViewMenuInSiteMap;
                }
                else
                    this.ShowOverlay(false);
            }
            else
            {
                // Add it
                var siteMap = xmlDoc.selectSingleNode("//SiteMap");
                if (siteMap != null) {
                    
                    var quickViewXml = this.LoadXMLDoc("QuickViewMenuSiteMapArea.xml");
                    var sXml = this.GetXMLStringFromDocument(quickViewXml);


                    if (sXml != null && sXml != "") {
                        
                        var quickViewDoc = this.ConvertXmlStringToDocument(sXml);

                        //var quickViewDoc = new ActiveXObject('Msxml2.DOMDocument.6.0');
                        //quickViewDoc.loadXML(quickViewXml.xml);

                        var quickViewNode = quickViewDoc.selectSingleNode("//Area")
                        if (quickViewNode != null) {

                            // Add as first sitemap item
                            siteMap.insertBefore(quickViewNode, siteMap.childNodes.item(0));

                           
                            var sXml = this.GetXMLStringFromDocument(siteMap);

                            this.UploadSiteMap(sXml)

                            this.siteMapXml = sXml;
                            this.quickViewMenuInSiteMap = !this.quickViewMenuInSiteMap;
                        }
                    }
                }
                else
                    this.ShowOverlay(false);
            }
        }
        else
            this.ShowOverlay(false);
    },

    UploadSiteMap : function (xml){

        if(this.siteMapId != null && xml != null && xml != ""){

            var sitemap = {};
            sitemap.SiteMapXml = xml;

            SDK.REST.updateRecord(this.siteMapId, sitemap, "SiteMap",
            function () {

                this.DXTools.QuickView.Config.PublishSiteMap();

            },
            function (error) {

                this.DXTools.QuickView.Config.ShowOverlay(false);
                alert(error);

            });

            
            
        }
    

    },


    PublishSiteMap: function () {

        var soapXmlDoc = this.LoadXMLDoc("PublishSiteMapSoapXml.xml");
        var soapXml = this.GetXMLStringFromDocument(soapXmlDoc);


         if (soapXmlDoc != null && soapXml != "") {

            //var soap = envelope.xml.replace("@SiteMapId", this.siteMapId);


             var envelope = soapXmlDoc.selectSingleNode("//s:Envelope");
             var envelopeXml = this.GetXMLStringFromDocument(envelope)
             if (envelope != null && envelopeXml != null) {
                var req = new XMLHttpRequest();
                req.open("POST", this.context.getClientUrl() + "/XRMServices/2011/Organization.svc/web", true);
                req.setRequestHeader("Accept", "application/xml, text/xml, */*");
                req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
                req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
                req.onreadystatechange = function () {
                    if (this.readyState == 4 /* complete */) {
                        if (this.status == 204 || this.status == 1223) {
                            //successCallback();
                        }
                        else {
                        }

                        // reinitialise window
                        DXTools.QuickView.Config.Initialise();
                    }
                };
                req.send(envelopeXml);
            }
        }
    },
    PublishWebResource: function (WebResourceId) {

        var soapXmlDoc = this.LoadXMLDoc("PublishWebResourceSoapXml.xml");
        var soapXml = this.GetXMLStringFromDocument(soapXmlDoc);


        if (soapXmlDoc != null && soapXml != "") {
            var envelope = soapXmlDoc.selectSingleNode("//s:Envelope");
            var envelopeXml = this.GetXMLStringFromDocument(envelope)
            envelopeXml = envelopeXml.replace("@WebResourceId", WebResourceId);

            if (envelope != null && envelopeXml != null) {
                var req = new XMLHttpRequest();
                req.open("POST", this.context.getClientUrl() + "/XRMServices/2011/Organization.svc/web", true);
                req.setRequestHeader("Accept", "application/xml, text/xml, */*");
                req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
                req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
                req.onreadystatechange = function () {
                    if (this.readyState == 4 /* complete */) {
                        if (this.status == 204 || this.status == 1223) {
                            //successCallback();
                        }
                        else {
                        }

                        // reinitialise window
                        DXTools.QuickView.Config.Initialise();
                    }
                };
                req.send(envelopeXml);
            }
        }
    }
    ,

    UpdateSecurityStatus : function(){

        this.ShowOverlay(true);


        if ( this.configXmlDoc) {
            
            if( this.configXmlDoc.selectSingleNode("//Config/Security[@Enabled='true']") != null)
            {
                // remove it
                if (this.configXmlDoc.selectSingleNode("//Config/Security") != null) {
                   
                    this.configXmlDoc.selectSingleNode("//Config/Security").setAttribute("Enabled", "false");
                                       
                    var sXml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + this.GetXMLStringFromDocument(this.configXmlDoc.selectSingleNode("//Config"));
                    this.UploadWebResource('dxtools_/QV/QuickViewMenuConfig.xml', sXml);

                }
                else
                    this.ShowOverlay(false);
            }
            else
            {
                // Add it
                if (this.configXmlDoc.selectSingleNode("//Config/Security") != null) {
                   
                    this.configXmlDoc.selectSingleNode("//Config/Security").setAttribute("Enabled", "true");
                                       
                    var sXml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + this.GetXMLStringFromDocument(this.configXmlDoc.selectSingleNode("//Config"));
                    this.UploadWebResource('dxtools_/QV/QuickViewMenuConfig.xml', sXml);
                
                }
                else
                    this.ShowOverlay(false);
            }
        }
        else
            this.ShowOverlay(false);
},

UploadWebResource : function (uniqueName, content){

    if (uniqueName != null && content != null && content != "") {

        SDK.REST.retrieveMultipleRecords("WebResource", "$select=WebResourceId&$filter=Name eq '" + uniqueName + "'",
               function (data) {

                   if (data[0] != null) {
                       // Found web resource so update it

                       var webresource = {};
                       webresource.Content = base64_encode(content);

                       SDK.REST.updateRecord(data[0].WebResourceId, webresource, "WebResource",
                       function () {

                           this.DXTools.QuickView.Config.PublishWebResource(data[0].WebResourceId);

                       },
                       function (error) {

                           this.DXTools.QuickView.Config.ShowOverlay(false);
                           alert(error);

                       });

                   }

               },
               function (error) {

                   alert(error);

               },
               function () {
                   
               });

    }
    

}



,

OpenColourProfile:function()
{
    window.open(this.context.getServerUrl() + "//WebResources/dxtools_/QV/QuickViewMenuColourProfile.htm","_self");
},

    //
    // Load xml document from url
    //
    LoadXMLDoc: function (url) {
        if (window.ActiveXObject) {
            xhttp = new ActiveXObject("Msxml2.XMLHTTP.3.0");
        }
        else {
            xhttp = new XMLHttpRequest();
        }
        xhttp.open("GET", url, false);
        xhttp.send("");
        return xhttp.responseXML;
    },

    ShowOverlay : function(displayOverlay){
        if(displayOverlay)
            document.getElementById("uxOverlay").style.display = "block";
        else
            document.getElementById("uxOverlay").style.display = "none";
    },
    
    ConvertXmlStringToDocument: function (xmlString) {
        var xmlDoc = null;
        if (window.ActiveXObject) {
            xmlDoc = new ActiveXObject('Msxml2.DOMDocument.6.0');
            xmlDoc.loadXML(xmlString);
        } else {
            var parser = new DOMParser();
            xmlDoc = parser.parseFromString(xmlString, "text/xml");
        }
        return xmlDoc;
    },
    GetXMLStringFromDocument : function(Doc){
        var xml = null;

        if (Doc.xml)
            xml = Doc.xml;
        else {
            var serializer = new XMLSerializer();
            xml = serializer.serializeToString(Doc);

        }
        return xml;
    },

    __namespace: true
};


function base64_encode(data) {
    // From: http://phpjs.org/functions
    // +   original by: Tyler Akins (http://rumkin.com)
    // +   improved by: Bayron Guevara
    // +   improved by: Thunder.m
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Pellentesque Malesuada
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Rafał Kukawski (http://kukawski.pl)
    // *     example 1: base64_encode('Kevin van Zonneveld');
    // *     returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
    // mozilla has this native
    // - but breaks in 2.0.0.12!
    //if (typeof this.window['btoa'] === 'function') {
    //    return btoa(data);
    //}
    var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
        ac = 0,
        enc = '',
        tmp_arr = [];

    if (!data) {
        return data;
    }

    do { // pack three octets into four hexets
        o1 = data.charCodeAt(i++);
        o2 = data.charCodeAt(i++);
        o3 = data.charCodeAt(i++);

        bits = o1 << 16 | o2 << 8 | o3;

        h1 = bits >> 18 & 0x3f;
        h2 = bits >> 12 & 0x3f;
        h3 = bits >> 6 & 0x3f;
        h4 = bits & 0x3f;

        // use hexets to index into b64, and append result to encoded string
        tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
    } while (i < data.length);

    enc = tmp_arr.join('');

    var r = data.length % 3;

    return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);

}

